package com.tsoj.tsojuserservice.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsoj.common.ErrorCode;
import com.tsoj.constant.CommonConstant;
import com.tsoj.context.ThreadLocalContext;
import com.tsoj.exception.BusinessException;
import com.tsoj.model.dto.user.UserLoginDto;
import com.tsoj.model.dto.user.UserQueryDto;
import com.tsoj.model.dto.user.UserRegisterDto;
import com.tsoj.model.po.User;
import com.tsoj.model.vo.LoginUserVO;
import com.tsoj.model.vo.UserVO;
import com.tsoj.propertise.JwtPropertise;
import com.tsoj.tsojuserservice.mapper.UserMapper;
import com.tsoj.tsojuserservice.service.UserService;
import com.tsoj.utils.JwtUtils;
import com.tsoj.utils.RedisUtils;
import com.tsoj.utils.SqlUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.tsoj.common.ErrorCode.PARAMS_ERROR;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
* @author 孙金硕
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-04-15 10:00:16
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Resource
    private JwtPropertise jwtPropertise;
    @Autowired
    private RedisUtils redisUtils;
    //注册用户
    @Override
    public long registerUser(UserRegisterDto userRegisterDto) {
        //先验证参数是否合法
        String account = userRegisterDto.getUserAccount();
        String password = userRegisterDto.getUserPassword();
        String checkPassword = userRegisterDto.getCheckPassword();
        //参数验证
        if(StringUtils.isAnyBlank(account,password,checkPassword)){
            throw new BusinessException(PARAMS_ERROR, "参数传入不正确");
        }
        if(!password.equals(checkPassword)){
            throw new BusinessException(PARAMS_ERROR, "两次密码不一致");
        }
        if(account.length() < 6 || account.length() > 16){
            throw new BusinessException(PARAMS_ERROR, "账号长度不正确");
        }
        if(password.length() < 6 || password.length() > 10){
            throw new BusinessException(PARAMS_ERROR, "密码长度不正确");
        }

        //确定账户唯一性
        synchronized (userRegisterDto.getUserAccount().intern()){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("useraccount",userRegisterDto.getUserAccount());
            if(userMapper.selectOne(userQueryWrapper) != null){
                throw new BusinessException(PARAMS_ERROR, "账号已存在");
            }
            //密码加密
            String encryptPassword = DigestUtils.md5DigestAsHex(userRegisterDto.getUserPassword().getBytes());
            // 插入数据
            User user = new User();
            user.setUseraccount(userRegisterDto.getUserAccount());
            user.setUserpassword(encryptPassword);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public Wrapper<User> getQueryWrapper(UserQueryDto userQueryDto) {
        if (userQueryDto == null) {
            throw new BusinessException(PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryDto.getId();
        String unionId = userQueryDto.getUnionId();
        String mpOpenId = userQueryDto.getMpOpenId();
        String userName = userQueryDto.getUserName();
        String userProfile = userQueryDto.getUserProfile();
        String userRole = userQueryDto.getUserRole();
        String sortField = userQueryDto.getSortField();
        String sortOrder = userQueryDto.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(unionId), "unionId", unionId);
        queryWrapper.eq(StringUtils.isNotBlank(mpOpenId), "mpOpenId", mpOpenId);
        queryWrapper.eq(StringUtils.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StringUtils.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.like(StringUtils.isNotBlank(userName), "userName", userName);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;

    }

    @Override
    public LoginUserVO login(UserLoginDto loginDto) {
        String account = loginDto.getUserAccount();
        String password = loginDto.getUserPassword();
        if(StringUtils.isAnyBlank(account,password)){
            throw new BusinessException(PARAMS_ERROR, "参数传入不正确");
        }
        if(account.length() < 6 || account.length() > 16){
            throw new BusinessException(PARAMS_ERROR, "账号长度不正确");
        }
        if(password.length() < 6 || password.length() > 10){
            throw new BusinessException(PARAMS_ERROR, "密码长度不正确");
        }

        //查库
        //密码加密后进行对比
        String encryptPassword = DigestUtils.md5DigestAsHex(loginDto.getUserPassword().getBytes(StandardCharsets.UTF_8));
        User user = this.query().eq("useraccount",account)
                .eq("userpassword",encryptPassword)
                .one();
        if(user == null){
            throw new BusinessException(PARAMS_ERROR, "用户不存在");
        }

        //根据账户和用户名生成token 做持久化校验
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("userRole", user.getUserrole());
        String jwt = JwtUtils.createJwt(map, jwtPropertise);
        redisUtils.set(jwt,user.getId() , jwtPropertise.getUserTtl(), MILLISECONDS);
        LoginUserVO loginUserVO = LoginUserVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .userAvatar(user.getUseravatarurl())
                .userProfile(user.getUserprofile())
                .userRole(user.getUserrole())
                .token(jwt)
                .createTime(user.getCreatetime())
                .updateTime(user.getUpdatetime())
                .build();

        return loginUserVO;
    }
    //todo第二版
    public LoginUserVO login1(UserLoginDto loginDto) {
        String account = loginDto.getUserAccount();
        String password = loginDto.getUserPassword();
        if(StringUtils.isAnyBlank(account,password)){
            throw new BusinessException(PARAMS_ERROR, "参数传入不正确");
        }
        if(account.length() < 6 || account.length() > 16){
            throw new BusinessException(PARAMS_ERROR, "账号长度不正确");
        }
        if(password.length() < 6 || password.length() > 10){
            throw new BusinessException(PARAMS_ERROR, "密码长度不正确");
        }

        //查库
        //密码加密后进行对比
        String encryptPassword = DigestUtils.md5DigestAsHex(loginDto.getUserPassword().getBytes(StandardCharsets.UTF_8));
        User user = this.query().eq("useraccount",account)
                .eq("userpassword",encryptPassword)
                .one();
        if(user == null){
            throw new BusinessException(PARAMS_ERROR, "用户不存在");
        }
        //根据账户和用户名生成token 做持久化校验
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("userRole", user.getUserrole());
        String token = JwtUtils.createJwt(map, jwtPropertise);
        //加入存储在redis放置token放出后不受控制
        redisUtils.set(token,user.getId(),jwtPropertise.getUserTtl(), MILLISECONDS);
        LoginUserVO loginUserVO = LoginUserVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .userAvatar(user.getUseravatarurl())
                .userProfile(user.getUserprofile())
                .userRole(user.getUserrole())
                .token(token)
                .createTime(user.getCreatetime())
                .updateTime(user.getUpdatetime())
                .build();

        return loginUserVO;
    }
    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollectionUtils.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());

    }
    //判断是否为管理员
    @Override
    public boolean isAdmin(long id) {
        if(id <= 0){
            throw new BusinessException(PARAMS_ERROR);
        }
        User user = this.getById(id);
        String userRole = user.getUserrole();
        System.out.println(userRole);
        if(userRole.equals("admin")){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public User getLoginUser() {
        //todo
        Long userId = ThreadLocalContext.getUserId();

        if(userId == null){
            throw new BusinessException(PARAMS_ERROR);
        }
        User user = this.getById(userId);
        return user;
    }

    //对象转包装类
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
}




